package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.beans.Beans;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
   @Transactional
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //1 参数校验
       String name = dto.getName();
       String logPwd = dto.getPassword();
       //判断用户名和密码是否存在
       if (StringUtils.isBlank(name)||StringUtils.isBlank(logPwd)) {
           CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码错误");
       }
       //2 根据用户名查询用户信息
       AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
       //校验用户名是否存在
       if (adUser==null) {
           CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该用户不存在");
       }
       //校验用户名的状态是否正常
       if (adUser.getStatus().intValue() !=9) {
           CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常，请联系管理员");
       }
       //3 获取数据库密码和盐， 匹配密码
       String realPwd = adUser.getPassword();
       String salt = adUser.getSalt();
       String saltPwd = DigestUtils.md5DigestAsHex((logPwd + salt).getBytes());
       // 用户输入密码（加密后）
       if (!saltPwd.equals(realPwd)) {
           CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户名或者密码错误");
       }
        //4 修改登录时间
       adUser.setLoginTime(new Date());
       this.updateById(adUser);
        //5 颁发token jwt 令牌
       String token = AppJwtUtil.getToken(adUser.getId().longValue());
       // 用户信息返回 VO
       AdUserVO adUserVO = new AdUserVO();
       BeanUtils.copyProperties(adUser,adUserVO);
        //6 返回结果（jwt）
       Map map = new HashMap();
       map.put("token",token);
       map.put("user",adUserVO);
       return ResponseResult.okResult(map);
    }
}
